import Taro from "@tarojs/taro"
import React, { useEffect, useRef, useState } from 'react'
import { Block, View, Canvas, Text } from '@tarojs/components'
import { CanvasTouchEvent } from '@tarojs/components/types/common'
import { canvasToTempFilePath, getDomInfo } from '@/path/acrossAPI'
import Signature from "./darg"
import { observer } from 'mobx-react'
import { BaseRouter } from "@/path/router";
import { uploadFile } from "@/path/service/request/uploadOld";
import { userStore } from "@/store";
import { Button } from "@taroify/core"
import './index.scss'
import './index.scss'
function Index() {

  const [loading, setLoading] = useState(false)
  /**magnify(画板缩放比例) rule(画板移动相对应需要增加的大小倍数) */
  const magnify = 0.5, rule = 1 / magnify, lineWidth = 5
  const signatureRef = useRef<Signature>()
  /**生成新签字图片的canvas宽高 */
  const [createCanvasWh, setCreateCanvasWh] = useState({
    width: 0,
    height: 0,
  })

  /**手指开始移动 */
  function onTouchstart(ev: CanvasTouchEvent) {
    const _p = ev.touches[0]
    signatureRef.current?.onDrawStart(_p.x, _p.y)
  }
  /**手指移动 */
  function onTouchmove(ev: CanvasTouchEvent) {
    const _p = ev.touches[0]
    signatureRef.current?.onDrawMove(_p.x, _p.y)
  }
  /**手指移动结束 */
  function onTouchEnd() {
    signatureRef.current?.onDrawEnd()
  }
  // 样例1初始化
  function initSignature() {
    getDomInfo('#canvasSignatureCanvas').then((res) => {
      const ctx = Taro.createCanvasContext("signatureCanvas");
      setCreateCanvasWh({
        width: res.height,
        height: res.width,
      })
      signatureRef.current = new Signature(ctx, {
        width: res.width,
        height: res.height,
        scale: 1,
        bgColor: '#fff',
        // toDataURL: (type, quality) => canvas.toDataURL(type, quality),
        // requestAnimationFrame: (fn) => canvas.requestAnimationFrame(fn),
        // getImagePath: () => new Promise((resolve, reject) => {
        //   const img = canvas.createImage();
        //   img.onerror = reject;
        //   img.onload = () => resolve(img);
        //   img.src = canvas.toDataURL();
        // })
      })
    })
  }

  /**确认签名 */
  function onAffirm() {
    setLoading(true)
    getDomInfo(`#canvasSignatureCanvas`).then((res) => {
      return canvasToTempFilePath({
        x: 0,
        y: 0,
        width: res.width,
        height: res.height,
        destWidth: res.width,
        destHeight: res.height,
        canvasId: "signatureCanvas",
      })
    }).then((canvasRes) => {
      /**翻转图片 */
      return onCreateImg(canvasRes.tempFilePath)
    }).then(() => {
      /**生成翻转后的图片 */
      return canvasToTempFilePath({
        x: 0,
        y: 0,
        width: createCanvasWh.width,
        height: createCanvasWh.height,
        destWidth: createCanvasWh.width,
        destHeight: createCanvasWh.height,
        canvasId: "createSignature",
      })
    }).then((createCanvasRes) => {
      uploadFile({
        header: {
          token: userStore.userInfo.token
        },
        url: "/recycleUser/signature",
        filePath: createCanvasRes.tempFilePath,
        name: "file"
      }).then(() => {
        BaseRouter.back({ data: true })
      }).finally(() => {
        setLoading(false)
      })
    }).finally(() => {
      setLoading(false)
    })
  }

  /**旋转并且保存图片 */
  function onCreateImg(src: string) {
    return new Promise((resolve, reject) => {
      // ToastLoading("绘制中...")
      try {
        const createContext = Taro.createCanvasContext("createSignature")
        //画背景图片
        createContext.fillStyle = 'white';
        createContext.fillRect(0, 0, createCanvasWh.width, createCanvasWh.height);
        createContext.strokeStyle = '#000000';
        createContext.translate(0, createCanvasWh.height);
        createContext.rotate(-90 * Math.PI / 180);
        createContext.drawImage(src, 0, 0, createCanvasWh.height, createCanvasWh.width);
        createContext.draw()
        setTimeout(() => {
          resolve(true)
          // ToastHideLoading()
        }, 600);
      } catch (error) {
        reject()
        // ToastHideLoading()
      }
    })
  }
  useEffect(() => {
    setTimeout(() => {
      initSignature()
    }, 100);
  }, [])
  return <>
    <View className="signature-page">
      <View className='signature-page-operation bg-gray-8'>
        <Button className='signature-page-btn bg-main c-white s-lg' color="primary" onClick={initSignature}>重置</Button>
        <Button className='signature-page-btn bg-main c-white s-lg' color="primary" loading={loading} onClick={onAffirm}>确认签署协议</Button>
      </View>
      {/* 画板 */}
      <Canvas canvas-id="signatureCanvas" id="canvasSignatureCanvas" onTouchStart={onTouchstart} onTouchMove={onTouchmove} onTouchEnd={onTouchEnd}
        disable-scroll className='signature-page-canvas'></Canvas >
      <View className='signature-page-title bg-gray-8'><Text className="signature-title c-black s-btn">请签字</Text></View>
      {/* 翻转图片 */}
      <Canvas canvas-id="createSignature" className='signature-page-canvas-create' style={{ width: createCanvasWh.width, height: createCanvasWh.height }}></Canvas>
    </View >
  </>
}

const Higher = React.memo(observer(Index))
export default () => <Block><Higher /></Block>

